package com.base.thread.carperson;

/**
 * 能量系统，遵循能量守恒定律
 * 实现能量转移、能量总和计算、能量个体计算（3个行为）函数、方法
 *
 * @author innocent
 * @date 2019/1/25 10:39
 */
public class EnergeySystem {

    /** 一个能量盒子，存储能量 */
    private double[] energeyBox;

    /** 锁对象 */
    private Object lock = new Object();

    /**
     * 有参构造
     *
     * @param n              能量盒子中能量的个数
     * @param initialEnergey 每个能量的初始值
     * @author ABC
     * @time 2019/1/25 10:50
     */
    public EnergeySystem(double initialEnergey, int n) {
        energeyBox = new double[n];
        for (int i = 0; i < energeyBox.length; i++) {
            energeyBox[i] = initialEnergey;
        }
    }

    public EnergeySystem() {
    }

    /**
     * 能量转移函数
     *
     * @param from  能量源
     * @param to    目标能量
     * @param amout 转移的能量值
     */
    public void transfer(int from, int to, double amout) {
        synchronized (lock) {
            while (energeyBox[from] < amout) {
                try {
                    //当条件不满足，将当前线程放入 Wait Set
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName());
            energeyBox[from] -= amout;
            System.out.printf("从%d转移%10.2f能量到%d", from, amout, to);
            energeyBox[to] += amout;
            System.out.printf("能量总和,%10.2f%n", getTotalEnergey());
        }
    }

    /**
     * 获取能量的总和
     */
    private double getTotalEnergey() {
        double sum = 0;
        for (double box : energeyBox) {
            box += sum;
        }
        return sum;
    }

    /**
     * 返回能量体个数
     */
    public int getCount() {
        return energeyBox.length;
    }


    public static void main(String[] args) {
    }
}
